<!--
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2022-04-25 23:04:04
 * @LastEditTime: 2022-04-25 23:10:01
 * @FilePath: \WebSkillExtend\eg15-三叔之和\index.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var threeSum = function (nums) {
        if (nums.length < 3) return [];

        let justNums = []; // 正数
        let lossNums = []; // 负数
        let zeroNums = [];

        nums.forEach((ele) => {
          if (ele > 0) {
            justNums.push(ele);
          } else if (ele < 0) {
            lossNums.push(ele);
          } else {
            zeroNums.push(ele);
          }
        });

        let lastArr = [];
        if (zeroNums.length > 2) {
          lastArr.push([0, 0, 0]);
        }
        let map = new Map();
        let minArr = [];
        let maxArr = [];
        // if (lossNums.includes(0)) {
        //     maxArr = lossNums
        //     minArr = justNums
        // } else
        if (lossNums.length > justNums.length) {
          lossNums.push(...zeroNums);
          maxArr = lossNums;
          minArr = justNums;
        } else {
          justNums.push(...zeroNums);
          maxArr = justNums;
          minArr = lossNums;
        }

        // 从小到大排序
        maxArr = maxArr.sort((a, b) => a - b);
        minArr = minArr.sort((a, b) => a - b);

        console.log(maxArr, minArr);

        for (let i = 0; i < maxArr.length; i++) {
          let a = maxArr[i];
          for (let k = i + 1; k < maxArr.length; k++) {
            let b = maxArr[k];
            let sum = a + b;
            // debugger;
            let result = minArr.find((ele) => sum + ele == 0);
            if (result && !map.get(`${a},${b}`)) {
              map.set(`${a},${b}`, true);
              lastArr.push([a, b, result]);
            }
          }
        }
        for (let i = 0; i < minArr.length; i++) {
          let a = minArr[i];
          for (let k = i + 1; k < minArr.length; k++) {
            let b = minArr[k];
            let sum = a + b;
            let result = maxArr.find((ele) => sum + ele == 0);
            if (result && !map.get(`${a},${b}`)) {
              map.set(`${a},${b}`, true);
              lastArr.push([a, b, result]);
            }
          }
        }
        return lastArr;
      };
      let result = threeSum([3, 0, -2, -1, 1, 2, -3]);
      console.log(result);
    </script>
  </body>
</html>
